<?php
session_start();
require_once($_SERVER['DOCUMENT_ROOT'].'../system/config.php');
require_once($INCLUDE_DIR.'recaptcha/recaptchalib.php');
$privatekey = "6LeQJAcAAAAAAGTE6f-AuOIAR_NpOGBEXKHWmCk4";
// check first, last, and email
if (isset($_POST['first']) && $_POST['first'] != '') {
	$_SESSION['first'] = $_POST['first'];
}
if (isset($_POST['last']) && $_POST['last'] != '') {
	$_SESSION['last'] = $_POST['last'];
}
if (isset($_POST['email']) && $_POST['email'] != '') {
	$_SESSION['email'] = $_POST['email'];

}
// check username set
if (!isset($_POST['username']) || $_POST['username'] == '') {
	$_SESSION['error'] = 'Missing required field: username';
	header('Location: '.$_SERVER['Document_ROOT'].'register.php');
	exit();
}
else {
	$username = $_POST['username'];
	$_SESSION['username'] = $username;
}

// check password set
if (!isset($_POST['password']) || !isset($_POST['repassword'])
		|| $_POST['password'] == '' || $_POST['repassword'] == '') {
	$_SESSION['error'] = 'Missing required field: password';
	header('Location: '.$_SERVER['Document_ROOT'].'register.php');
	exit();
}
else {
	$pass = $_POST['password'];
	$repass = $_POST['repassword'];
}	

// check password matches
if ($pass != $repass) {
	$_SESSION['error'] = 'Passwords did not match. Please try again.';
	header('Location: '.$_SERVER['Document_ROOT'].'register.php');
	exit();
}

// check valid captcha response
$resp = recaptcha_check_answer ($privatekey,
				$_SERVER["REMOTE_ADDR"],
				$_POST["recaptcha_challenge_field"],
				$_POST["recaptcha_response_field"]);

if (!$resp->is_valid) {
	$_SESSION['error'] = 'The reCAPTCHA was entered incorrectly. Please try again.';
	header('Location: '.$_SERVER['Document_ROOT'].'register.php');
	exit();
}

// open database
// fail on database errors
try {
	$db = new PDO("sqlite:".$DATABASE);
} catch (PDOException $e) {
	die('Sorry, there is a problem with the database');
}

// check if username already exists
$query = "SELECT COUNT(username) as cnt FROM user WHERE username = :username";
$stmt = $db->prepare($query);
$stmt->bindParam(':username', $username);
$stmt->execute();

$result = $stmt->fetch(PDO::FETCH_ASSOC);
if ($result === false) {
	die('Sorry, there was an error with the database');
}
if ($result['cnt'] > 0) {
	$_SESSION['error'] = 'The username you requested, <strong>'.$username.'</strong>, has already been taken. Please try another.';
	header('Location: '.$_SERVER['Document_ROOT'].'register.php');
	exit();
}

// insert user into database
$insert = "INSERT INTO user (username, password, activated, usergroup";
$values = " VALUES (:uname, :pass, '0', 'whatsinvasive'";
$param = array();
$param[':uname'] = $username;
$param[':pass'] = md5($pass);


if (isset($_POST['first']) && $_POST['first'] != '') {
	$insert .= ', first';
	$values .= ', :first';
	$param[':first'] = $_POST['first'];
}

if (isset($_POST['last']) && $_POST['last'] != '') {
	$insert .= ', last';
	$values .= ', :last';
	$param[':last'] = $_POST['last'];
}

if (isset($_POST['email']) && $_POST['email'] != '') {
	$insert .= ', email';
	$values .= ', :email';
	$param[':email'] = $_POST['email'];
}

$insert .= ') '.$values.')';

$insertstmt = $db->prepare($insert);
$insertstmt->execute($param) or die('Sorry, there is a problem with the database');

/*
$sqlquery = "SELECT ROWID FROM user WHERE username = :uname";
$stmt = $db->prepare($sqlquery);
$stmt->bindValue(':uname',$username, PDO::PARAM_STR);
$stmt->execute();
$res = $stmt->fetch();
$rowID = $res[0];
$randStr = generateString(10);
$hash = md5($rowID . $randStr);
$to      = $_SESSION['email'];
$subject = 'Activate your account - What\'s Invasive';
$message = "Dear $username,\nThanks for registering an account on What's Invasive. To complete your activation, simply copy and paste the address below into your web browser. \n\n www.whatsinvasive.com/accountactivation?val=" .urlencode($hash). "&row=$rowID&string=$randStr\nThank you again, and we look forward to receiving many email submissions from you in the future.\n\nSincerely,\nThe WhatsInvasive Team";
$headers = 'From: emailactivation@whatsinvasive.com' . "\r\n" .
    'Reply-To: contact@whatsinvasive.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
session_destroy();
*/
?>

<html>
<head>
        <link rel="stylesheet" href="<?=$CSS_DIR?>blueprint/miniscreen.css" type="text/css" media="screen, projection" />
         <!--[if IE]><link rel="stylesheet" href="<?=$CSS_DIR?>blueprint/ie.css" type="text/css" media="screen, projection" /><![endif]-->

        <!-- for iphone -->
        <meta name="viewport" content="width=device-width; initial-scale=.8; maximum-scale=1.0; user-scalable=0;" />

</head>
<body>
<div class="container">
        <div class="span-8 last success">
		Thank you for your participation. You have been registered!
	</div>
</div>
</body>
</html>
<?php
/*
function generateString($length=9) {
	$vowels = 'aeuyAEUY';
	$consonants = 'bdghjmnpqrstvzBDGHJLMNPQRSTVWXZ23456789';
	$string = '';
	$alt = time() % 2;
	for ($i = 0; $i < $length; $i++) {
		if ($alt == 1) {
			$string .= $consonants[(rand() % strlen($consonants))];
			$alt = 0;
		} else {
			$string .= $vowels[(rand() % strlen($vowels))];
			$alt = 1;
		}
	}
	return $string;
}
*/
?>
